import hashlib
import logging
from tkinter import ttk
from tkinter import messagebox

# 初始化日志记录器
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 样式注册函数
STYLE_REGISTRY = set()

def _register_style_safely(style_name, style_config):
    """安全注册样式，避免重复注册"""
    if style_name in STYLE_REGISTRY:
        logger.debug(f"样式 {style_name} 已注册，跳过。")
        return

    try:
        ttk.Style().configure(style_name, **style_config)
        STYLE_REGISTRY.add(style_name)
        logger.debug(f"样式 {style_name} 注册成功。")
    except Exception as e:
        logger.error(f"注册样式 {style_name} 失败: {e}")
        raise

def _generate_style_name(base_color):
    """生成唯一样式名称"""
    if not base_color.startswith("#") or len(base_color) != 7:
        raise ValueError("无效的颜色格式，必须是 #RRGGBB")

    hash_suffix = hashlib.md5(base_color.encode()).hexdigest()[:6]
    return f"ModernButton-{hash_suffix}"

def _lighten_color(hex_color, factor=0.2):
    """调整颜色亮度"""
    if not hex_color.startswith("#") or len(hex_color) != 7:
        raise ValueError("无效的颜色格式，必须是 #RRGGBB")

    r, g, b = int(hex_color[1:3], 16), int(hex_color[3:5], 16), int(hex_color[5:7], 16)
    r = min(255, int(r + (255 - r) * factor))
    g = min(255, int(g + (255 - g) * factor))
    b = min(255, int(b + (255 - b) * factor))

    return f"#{r:02X}{g:02X}{b:02X}"

def create_modern_button(parent, text, command, bg_color):
    """创建现代化按钮"""
    style_name = _generate_style_name(bg_color)

    # 安全注册样式
    _register_style_safely(style_name, {
        "background": bg_color,
        "foreground": "white",
        "relief": "flat",
        "padding": (10, 5)
    })

    button = ttk.Button(parent, text=text, command=command, style=style_name)
    return button